package com.share51.config.mobile;

import org.springframework.core.Ordered;
import org.springframework.mobile.device.view.LiteDeviceDelegatingViewResolver;
import org.springframework.web.servlet.ViewResolver;

/**
 * @author gaobo
 * @version 1.0.0
 * @ClassName DeviceDelegatingViewResolverFactory
 * @Description TODO
 * @Date 2020/11/2 10:09
 */
public class DeviceDelegatingViewResolverFactory {
    private final DeviceDelegatingViewResolverProperties properties;

    public DeviceDelegatingViewResolverFactory(DeviceDelegatingViewResolverProperties properties) {
        this.properties = properties;
    }

    public LiteDeviceDelegatingViewResolver createViewResolver(ViewResolver delegate, int delegatingOrder) {
        LiteDeviceDelegatingViewResolver resolver = new LiteDeviceDelegatingViewResolver(delegate);
        resolver.setEnableFallback(this.properties.isEnableFallback());
        resolver.setNormalPrefix(this.properties.getNormalPrefix());
        resolver.setNormalSuffix(this.properties.getNormalSuffix());
        resolver.setMobilePrefix(this.properties.getMobilePrefix());
        resolver.setMobileSuffix(this.properties.getMobileSuffix());
        resolver.setTabletPrefix(this.properties.getTabletPrefix());
        resolver.setTabletSuffix(this.properties.getTabletSuffix());
        resolver.setOrder(delegatingOrder);
        return resolver;
    }

    public LiteDeviceDelegatingViewResolver createViewResolver(ViewResolver delegate) {
        if (!(delegate instanceof Ordered)) {
            throw new IllegalStateException("ViewResolver " + delegate + " should implement " + Ordered.class.getName());
        } else {
            int delegateOrder = ((Ordered) delegate).getOrder();
            return this.createViewResolver(delegate, this.adjustOrder(delegateOrder));
        }
    }

    private int adjustOrder(int order) {
        return order == -2147483648 ? -2147483648 : order - 1;
    }
}
